import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1'))
channel = connection.channel()

# 避免交换机未创建
channel.exchange_declare(exchange='logs2',  # 交换机名称
                         exchange_type='direct')  # 模式---关键字

result = channel.queue_declare('', exclusive=True)  # 创建队列，名字随机生成
queue_name = result.method.queue  # 获取队列名

# 把队列绑定到交换机
channel.queue_bind(exchange='logs2',
                   queue=queue_name,
                   routing_key='error')  # 关键字

channel.queue_bind(exchange='logs2',
                   queue=queue_name,
                   routing_key='info')  # 关键字

channel.queue_bind(exchange='logs2',
                   queue=queue_name,
                   routing_key='debug')  # 关键字

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)


# 监听队列（配置，还未监听，只是确认）
channel.basic_consume(queue=queue_name,
                      auto_ack=True,
                      on_message_callback=callback)

print(" [*] Waiting for")
channel.start_consuming()  # 开始消费
